package com.qf.ebook.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

@Controller
public class UploadController {


    @PostMapping("/upload")
    public String upload(MultipartFile pic, HttpSession session) throws IOException {
        //0. 校验图片真假
        BufferedImage image = ImageIO.read(pic.getInputStream());
        if(image == null){
            // 假图
            return null;
        }

        //1. 获取文件的原名字 (拿后缀)
        String originalFilename = pic.getOriginalFilename();    //skdjfhsdkjfh.dsjkfh.skdfsdf.jpg
        String suffixName = originalFilename.substring(originalFilename.lastIndexOf("."));   // .jpg
        //2. 生成新名称
        String newName = UUID.randomUUID().toString().replace("-","") + suffixName;  // askjfjsdgfdsgfdsifugsdf.jpg

        //3. 通过pic保存图片到本地
        String realPath = session.getServletContext().getRealPath("/upload/");
        File file = new File(realPath);
        if(!file.exists()){
            file.mkdirs();
        }
        File filePath = new File(file, newName);
        pic.transferTo(filePath);

        return null;
    }

}
